package com.tamo.ppresta.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.gyf.immersionbar.ImmersionBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.body.JsonBody;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tamo.ppresta.BuildConfig;
import com.tamo.ppresta.R;
import com.tamo.ppresta.base.BaseActivity;
import com.tamo.ppresta.base.BaseApplication;
import com.tamo.ppresta.bean.LoginBean;
import com.tamo.ppresta.constant.NET_CONSTANT;
import com.tamo.ppresta.constant.SPConstant;
import com.tamo.ppresta.http.HttpData;
import com.tamo.ppresta.httpapi.LoginApi;
import com.tamo.ppresta.json.ObjectToJsonUtil;
import com.tamo.ppresta.util.AESUtils;
import com.tamo.ppresta.util.ButtonUtils;
import com.tamo.ppresta.util.LogUtils;
import com.tamo.ppresta.util.MapUtils;
import com.tamo.ppresta.util.MyUtils;
import com.tamo.ppresta.util.PhoneHelperUtils;
import com.tamo.ppresta.util.SPUtil;
import com.tamo.ppresta.util.ToastUtil;
import com.tamo.ppresta.widget.VerificationCodeView;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author yeyang
 * @name ppresta
 * @class name：com.tamo.ppresta.activity
 * @class describe
 * @time 2022/12/19 19:24
 * @change
 * @chang time
 * @class describe
 */
public class VerificationCodeActivity extends BaseActivity {
    @BindView(R.id.iv_login_phone2)
    ImageView mIvLoginPhone2;
    @BindView(R.id.iv_xieyi)
    ImageView mIvXieyi;
    @BindView(R.id.tv_xieyi)
    TextView mTvXieyi;
    @BindView(R.id.tv_continuar)
    TextView mTvContinuar;
    @BindView(R.id.tv_verify_code_time)
    TextView mTvVerifyCodeTime;
    @BindView(R.id.verify_code_view)
    VerificationCodeView mVerifyCodeView;
    @BindView(R.id.iv_title_right)
    ImageView mIvTitleRight;
    @BindView(R.id.rl_title_right)
    RelativeLayout mRlTitleRight;
    @BindView(R.id.iv_title_back)
    ImageView mIvTitleBack;
    @BindView(R.id.rl_title_back)
    RelativeLayout mRlTitleBack;
    @BindView(R.id.tv_title_name)
    TextView mTvTitleName;

    private TimeCount time;

    @Override
    protected int setLayout() {
        return R.layout.activity_verification_code;
    }

    @Override
    protected void setView() {
        mVerifyCodeView.setInputCompleteListener(new VerificationCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                Toast.makeText(VerificationCodeActivity.this, "" + mVerifyCodeView.getInputContent(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void deleteContent() {

            }
        });
        time = new TimeCount(60000, 1000);
        time.start();
        mTvContinuar.setOnClickListener(this::onClick);
    }

    @Override
    protected void setData() {

    }

    @Override
    public void onClick(View v) {
        ButtonUtils.isFastDoubleClick();
        switch (v.getId()) {
            case R.id.rl_title_back:
                finish();
                break;
            case R.id.tv_continuar:
                ToastUtil.showShort(this, "登录");
//                login();
                ifHaveLoctionPermission();
                break;
        }
    }

    // 判断是否有相机权限
    private void ifHaveLoctionPermission() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean all) {
                        // 有权限
                        login();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtil.showShort(VerificationCodeActivity.this, "被永久拒绝授权，请手动打开位置权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(VerificationCodeActivity.this, permissions);
                        } else {
                            ToastUtil.showShort(VerificationCodeActivity.this, "获取位置权限失败");
                        }
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        MyUtils.setStatusBarVisible(this);
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                .statusBarDarkFont(true)
                .init();
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (time != null) {
            time.onFinish();
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mTvVerifyCodeTime != null) {
                mTvVerifyCodeTime.setText("Reenviar " + millisUntilFinished / 1000 + "S");
            }
        }

        @Override
        public void onFinish() {
            // TODO: 2022/12/19 倒计时时间走完 重新发送短信
        }
    }

    /**
     * 登录请求
     */
    private void login() {
        String privateKey = AESUtils.getPrivateKey(24);
        String privateKeyFront = AESUtils.getPrivateKeyFront(privateKey);
        String privateKeyBehind = AESUtils.getPrivateKeyBehind(privateKey);
        LogUtils.info(TAG, "随机秘钥：" + privateKey);
        LogUtils.info(TAG, "随机秘钥19：" + privateKeyFront);
        LogUtils.info(TAG, "随机秘钥5：" + privateKeyBehind);
        BaseApplication.getInstance().setEasyHttpHead(NET_CONSTANT.HEADER_SECRETKEY_NAME, privateKeyFront);
        LoginApi loginApi = new LoginApi().setLanguageCode(NET_CONSTANT.LANGUAGE_CODE)
                .setItemCode(NET_CONSTANT.ITEM_CODE)
                .setMobile("573101231231")
                .setPassword("123456")
                .setSmsCode("")
                .setInvitCode(NET_CONSTANT.INVIT_CODE)
                .setAppVersion((BuildConfig.VERSION_CODE) + "")
                .setAppPackage(BuildConfig.APPLICATION_ID)
                .setDeciveBrand(PhoneHelperUtils.getDeviceBrand())
                .setDeciveId(PhoneHelperUtils.getUUID())
                .setDeviceModel(PhoneHelperUtils.getModel())
                .setWifiStr(PhoneHelperUtils.getWifiName(getApplicationContext()))
                .setFlowCompanyCode("")
                .setFlowBindId("")
                .setPushPlatForm("")
                .setPushBindId("");

        Map<String, Object> stringObjectMap = MapUtils.objectToMap(loginApi);
        String json = ObjectToJsonUtil.getJson(stringObjectMap);
        LogUtils.info(TAG, json);
        String newJson = ObjectToJsonUtil.getNewJson(stringObjectMap);
        LogUtils.info(TAG, newJson);
        String aesEncrypt = AESUtils.aesEncrypt(newJson, privateKey, NET_CONSTANT.VIPARR);
        LogUtils.info(TAG, "加密： " + aesEncrypt);
        String aesDecrypt = AESUtils.aesDecrypt(aesEncrypt, privateKey, NET_CONSTANT.VIPARR);
        LogUtils.info(TAG, "解密： " + aesDecrypt);
        JsonBody jsonBody = new JsonBody(aesEncrypt + privateKeyBehind);

        EasyHttp.post(this).api(new LoginApi()).body(jsonBody).request(new OnHttpListener<HttpData<LoginBean>>() {
            @Override
            public void onSucceed(HttpData<LoginBean> result) {
                if (null != result && null != result.getData()) {
                    LogUtils.info(TAG, "data: " + result);
                    if (null != result.getData().getSessionId()) {
                        SPUtil.saveObject(getApplicationContext(), SPConstant.SP_NAME, SPConstant.SP_SESSIONID, result.getData().getSessionId());
                    }
                    SPUtil.saveObject(getApplicationContext(), SPConstant.SP_NAME, SPConstant.SP_IS_GOOGLE_AUDIT_ACCOUNT, result.getData().getIsGoogleAuditAccount());
                    startActivity(new Intent(VerificationCodeActivity.this, MainActivity.class));
                    VerificationCodeActivity.this.finish();
                } else {
                    LogUtils.info(TAG, "data: 是null");
                }
            }

            @Override
            public void onFail(Exception e) {
                LogUtils.info(TAG, "e: " + e.toString());
            }
        });
    }
}